<template>
    <div class="boxContentCss">
            <EdCreateCard title="新增巡检任务">
                <template #back>
                    <div class="createBack" @click="$utilsSet.goBack($router)" >
                        <svg-icon icon-class="back" /> 返回
                    </div>
                </template>
                <el-form class="width-m25" :model="form" :rules="rules" ref="ruleForm" label-position='right' label-width="120px">
                    <el-row :gutter="20">
                        <el-col :span="7">
                            <el-form-item class="width-m25" label="项目" prop="villageId" >
                            <EdSelect v-model="form.villageId" :selectParams="projectNameParams" style="width:100%" @input="projectChange" @emit-select-value="projectValueChange" ></EdSelect>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item class="width-m25"  label="任务名称" prop="patrolName" :rules="$validate.validates({required:true,msg:'请输入任务名称',type: 'producetName'})">
                                <el-input class="flex-input"  v-model="form.patrolName" placeholder="请输入任务名称" maxlength="50"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <div style="display:flex">
                                <el-form-item class="width-m25"  label="任务时间" prop="startTime" style="width: 57.7%;" >
                                        <el-date-picker style="width:100%" v-model="form.startTime" type="datetime" format="yyyy-MM-dd HH:mm"
                                            value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择开始时间"></el-date-picker>
                                </el-form-item>
                                <el-form-item class="time-form" prop="endTime" style="width: 42%">
                                    <el-date-picker style="width:100%" v-model="form.endTime" type="datetime" format="yyyy-MM-dd HH:mm"
                                            value-format="yyyy-MM-dd HH:mm:ss"
                                            placeholder="选择结束时间"></el-date-picker>
                                </el-form-item>
                            </div>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="7">
                            <el-form-item class="width-m25"  label="巡检类型" prop="patrolType">
                                <EdSelect v-model="form.patrolType" :selectParams="patrolTypeParams" style="width:100%" :formatter="setDicType" ref="selectpatrol" @input="onChange" ></EdSelect>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item class="width-m25"  label="巡检点位" prop="locationDTO" >
                                <template v-if="form.locationDTO.length > 0">
                                    <div style="display: flex; flex-direction: row;align-items: end;width: 100%">
                                        <el-scrollbar class="scrollbar" style="width:70%,height:128px" v-if="form.locationDTO.length > 0">
                                            <div v-for="(item,index) in form.locationDTO" :key="index" class="item">
                                                <span>{{item.name}}</span>
                                                <div @click="delPonit(index)"><i class="el-icon-close" style="cursor: pointer"></i></div>
                                            </div>
                                        </el-scrollbar>
                                    </div>
                                </template>
                                <template v-else>
                                    <el-button  @click="selectPoint()" class="ed-button ed_black-bottom">选择点位</el-button>
                                </template>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20" v-if="form.locationDTO.length > 0">
                        <el-col :span="12">
                            <el-form-item>
                                <el-button @click="selectPoint()" class="ed-button ed_black-bottom">选择点位</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="责任人" class="width-100" prop="personnelId">
                                <el-select v-model="form.personnelId" @change="handleRepairChange" :placeholder="recPersonParams.placeholder" class="transferStyle" style="width:100%" clearable>
                                    <el-option v-for="item in recPersonParams.options" :label="item['name']" :value="item['id']" :key="item['id']">
                                        <el-radio  :label="item.id">
                                            <span class="name">{{item.name}}</span>
                                            <span class="phone">{{item.mobile}}</span>
                                        </el-radio>
                                    </el-option>
                                </el-select>
                            </el-form-item> 
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item class="paddingBottom145 btnClass1">
                                    <el-button class="ed-button ed_black-bottom" @click="submit('ruleForm')" :loading="disabled">提 交</el-button>
                                    <el-button class="ed-button ed_white_bottom" @click="$utilsSet.goBack($router),dialogVisible = false">取 消</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>    
            </EdCreateCard>
            <EdDialog ref="dialogRef" v-if="showChoosePoint" title="请选择点位" @close-dialog="closeDialog" @save-dialog="saveDialog">
                <el-table
                    ref="multipleTable"
                    :data="tableData"
                    tooltip-effect="dark"
                    style="width: 100%"
                    class="tableStyle"
                    height="300px"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center"></el-table-column>
                    <el-table-column label="全选" prop="locationName" >
                    </el-table-column>
                    <el-table-column>
                        <template slot="header" slot-scope="scope" >
                            <el-input
                            v-model="queryPoint.locationName"
                            size="mini"
                            clearable
                            @blur="handleQuery"
                            @keyup.enter.native="handleQuery"
                            placeholder="输入关键字词"/>
                        </template>
                    </el-table-column>
                </el-table>
            </EdDialog>

    </div>
</template>

<script>
    import EdDialog from 'src/components/EdDialog.vue'
    import EdSelect from 'src/components/EdSelect.vue'
    import EdCreateCard from 'src/components/EdCreateCard.vue'
    import { defineComponent } from 'vue'
    import {addRow, getrRepairerData,projectList} from "./api.js"
    import {pointList} from "../point/api"
    import {getDictByCode} from "src/api/dictionaries";
    export default defineComponent({
        name: "projectCreate",
        components: { EdCreateCard,EdSelect,EdDialog },
        data(){
            const validatorStrat = (rule, value, callback) => {
                if(!value){
                    callback(new Error("请选择任务开始时间"))
                }else{
                    var startTime = new Date(Date.parse(value))
                    var endTime = new Date(Date.parse(this.form.endTime))
                    //进行比较
                    if(startTime > endTime) {
                        callback(new Error("开始时间不能大于结束时间"))
                    } else {
                        callback()
                    }
                    callback()
                }
            };
            const validatorEnd = (rule, value, callback) => {
                if(!value){
                    callback(new Error("请选择任务结束时间"))
                } else if(value) {
                    // 把字符串格式转换为日期类
                    var startTime = new Date(Date.parse(this.form.startTime))
                    var endTime = new Date(Date.parse(value))
                    //进行比较
                    if(startTime > endTime) {
                        callback(new Error("开始时间不能大于结束时间"))
                    } else {
                        callback()
                    }
                } else{
                    callback()
                }
            };
            return {
                rules:{
                    villageId: [
                        { required: true, message: '请选择项目', trigger: 'blur' },
                    ],
                    // patrolName: [
                    //     { required: true, message: '请输入任务名称', trigger: 'blur' },
                    // ],
                    patrolType: [
                        { required: true, message: '请选择点位类型', trigger: 'blur' },
                    ],
                    locationDTO: [
                        { required: true, message: '请选择点位', trigger: 'blur' },
                    ],
                    personnelId: [
                        { required: true, message: '责任人不能为空', trigger: 'blur' },
                    ],
                    startTime: [
                        { required: true, validator: validatorStrat,trigger: 'change' }
                    ],
                    endTime: [
                        { required: true, validator: validatorEnd,trigger: 'change' }
                    ],
                },
                form:{
                    startTime: "",
                    endTime: "",
                    locationDTO: [],
                    mobile: "",
                    patrolType: '',
                    patrolTypeName:'',
                    personnelId: '',
                    personnelName: "",
                    planName: "",
                    villageId: '',
                    villageName: "",
                    patrolName:''
                },
                projectNameParams:{
                    placeholder:"请选择项目名称",
                    options: [],
                },
                patrolTypeParams: {
                    placeholder:"请选择巡检类型",
                    options: [],
                    props: {label:"label", value:"value"}
                },
                showChoosePoint:false,
                checkAll:false,
                tableData: [],
                multipleSelection: [],
                search:'',
                disabled: false,
                queryPoint: {
                    page: 1,
                    pageSize: 99999,
                    locationName: '',
                    villageId:'',
                    villageName:''
                },
                recPersonParams: {
                    options: []
                },
                params : {
                    villageId: '',
                    userFunction: ''
                }
            }
        },
        created() {
            this.initDic()
        },
        activated(){
            this.initDic()
        },
        deactivated() {
            this.form = {
                startTime: "",
                endTime: "",
                locationDTO: [],
                mobile: "",
                patrolType: '',
                patrolTypeName:'',
                personnelId: '',
                personnelName: "",
                planName: "",
                villageId: '',
                villageName: "",
                patrolName:''
            }
            this.multipleSelection=[]
            this.$refs['ruleForm'].resetFields();
        },
        methods:{
            initDic(){
                projectList({page:1,pageSize:999999}).then(response => {
                    if(response.success) {
                        let options = response.data.records.map(x=>{return {label:x.villageName,value:x.villageId}})
                        this.projectNameParams.options=options
                    }
                })
                // 获取字典值方式
                getDictByCode("patrolType").then(response => {
                    if(response.success) {
                        this.patrolTypeParams.options=response.data.items
                    }
                })
                // 责任人
                
            },
            setDicType(row ,cloumn) {
                let options = this.patrolTypeParams.options.find(x => x.value == row.patrolType)
                return options.label
            },
            onChange(row){
                let userFunction_type='';
                if(row==0)  userFunction_type = '保安'
                if(row==1)  userFunction_type = '保洁'
                if(row==2)  userFunction_type = '工程'
                if(row==3)  userFunction_type = '绿化'
                
                this.params.villageId=this.form.villageId,
                this.params.userFunction=userFunction_type
                getrRepairerData(this.params).then(response => {
                    if(response.success) {
                        this.recPersonParams.options = response.data;
                    }
                })
            },
            selectPoint(){
                if(!this.form.villageId) {
                    this.$message.warning({
                        message: '请选择项目！',
                        duration: 2000,
                        center:true
                    });
                    return
                }
                this.handleQuery()
                this.showChoosePoint=true
            },
            closeDialog(){
                this.showChoosePoint=false
            },
            saveDialog(){
                this.showChoosePoint=false
                let ids = this.multipleSelection.map(x=>{return {id:x.id,name:x.locationName,locationType:x.locationType,url:x.url,villageName:x.villageName}})
                // console.log('ids',ids);
                this.form.locationDTO = ids
            },
           
            handleSelectionChange(val) {
                this.multipleSelection = val;
                // let ids= this.multipleSelection.map(x=>{return x.id})
                // this.form.locationId = ids
            },
            delPonit(index) {
                this.form.locationDTO.splice(index, 1)
            },
            submit(formName){
                this.form.patrolTypeName =this.$refs.selectpatrol.$el.__vue__.selectedLabel
                console.log(this.$refs.selectpatrol.$el.__vue__.selectedLabel)
                this.$refs[formName].validate((valid)=>{
                    if(!valid){
                        return
                    }
                    addRow(this.form).then(response => {
                        if(response.success) {
                            this.$message.success({
                                message: '新增任务成功！',
                                duration: 2000,
                                center:true
                            });
                            this.$router.back()
                        }
                    })
                })
            },
            // 责任人select
            handleRepairChange(value){
                // if(!this.form.villageId) {
                //     this.$message.warning({
                //         message: '请先选择项目！',
                //         duration: 2000,
                //         center:true
                //     });
                //     return
                // }
                // if(!this.form.patrolType) {
                //     this.$message.warning({
                //         message: '请选择巡检类型！',
                //         duration: 2000,
                //         center:true
                //     });
                //     return
                // }
                let obj = this.recPersonParams.options.find((v, i)=>{
                    return v.id == value
                })
                this.form.personnelId = obj['id']
                this.form.personnelName = obj['name']
                this.form.mobile = obj['mobile']
            },
            projectChange(row) {
                let option = this.projectNameParams.options.find(x=>x.value==row)
                this.form.villageName = option.label
                this.params.villageId=this.form.villageId
                this.form.personnelId =''
                if(this.params.userFunction) {
                    getrRepairerData(this.params).then(response => {
                        if(response.success) {
                            this.recPersonParams.options = response.data || []
                        }
                    })
                }
                
            },
            projectValueChange(row){
                this.handleQuery()
                this.form.locationDTO=[]
                this.multipleSelection=[]
            },
            // patrolTypeChange(row) {
            //     let option = this.patrolTypeParams.options.find(x=>x.value==row)
            //     this.form.patrolTypeName = option.label
            // },
            handleQuery() {
                this.queryPoint.villageId= this.form.villageId
                let options = this.projectNameParams.options.find(x=>x.value==this.queryPoint.villageId)
                this.form.villageName = options.label
                this.queryPoint.villageName= this.form.villageName
                pointList(this.queryPoint).then(response => {
                    if(response.success) {
                        this.tableData = response.data.records
                    }
                }).then(res=>{
                    this.toggleSelection()
                })
            },
            toggleSelection() {
                this.$nextTick(() => {
                    if (this.form.locationDTO && this.form.locationDTO.length > 0) {
                        // 找到选择的数据和列表相同的数据
                        let rows = this.tableData.filter(x => this.form.locationDTO.some(item => item.id == x.id))
                        rows.forEach(row => {
                            this.$refs.multipleTable.toggleRowSelection(row)
                        })
                    } else {
                        if(this.$refs.multipleTable)
                       this.$refs.multipleTable.clearSelection();
                    }
                })
            },
        },
        
    })
</script>

<style lang="scss" scoped>
.scrollbar {
    height: 150px;
    border: 1px solid #DCDFE6;
    border-radius: 2px;
    padding: 0 10px;
    width: 100%;
    .item {
        display: flex;
        align-content: center;
        justify-content: space-between;
        padding: 0 4px;
        border-radius: 2px;

        &:hover {
            background-color: bisque;
        }
    }
}

.boxContentCss{
    position: relative;
    padding-bottom: 150px;
    .el-form{
        padding: 45px 45px 15px 15px;
    }
}
.projectButton{
    position: absolute;
    bottom:50px;
    left:250px;
    border-radius: 20px;
}
.createBack{
    margin-right: 50px;
}
.time {
    .el-form-item__content {
        margin-left: 10px
    }
}
.checkboxPoint{
    display: flex;
    justify-content: space-between;
}
:deep .el-table .el-table__body-wrapper{
    &::-webkit-scrollbar-thumb{
        background-color: #C1C1C1;
        border-radius: 2px;
    }
}
:deep .time-form {
    margin-left: 10px;
    .el-form-item__content {
        margin-left: 5px !important;
    }
}
:deep .tableStyle {
    // tbody{
    //     transform: translateX(-4px) !important;

    // }
    .el-input__inner{
        border-radius: 8px;
    }
}
</style>